<?php

namespace app\tours\controller;

class Line extends Common {

        public function index() {
                if (!$_REQUEST['id']) {
                        $this->_empty();
                } else {
                        $this->assign('id', $_REQUEST['id']);
                }

                $Tours = D("Tours");
                //线路读取
                $this_line = $Tours->field(true)->relation(true)->cache()->find($_REQUEST['id']);
                if (empty($this_line)) {
                        return $this->_empty();
                }
                //面包屑
                $crumbs = array();
                if ($this_line['cid'] != '') {
                        $locationdetail = D('LocationDetail')->relation(true)->where(array('location_id' => array('in', $this_line['cid']), 'status' => '1'))->limit(10)->cache()->select();
                }
                $this->assign('ld', $locationdetail);




                $zone1 = M("Location")->field('id,name,write_string')->where(array('pid' => array('in', '1,2'), 'id' => array('in', $this_line['cid'])))->cache()->find();
                if ($zone1) {
                        $crumbs[] = array(
                            'name' => $zone1['name'],
                            'url' => U('/' . $zone1['write_string'])
                        );
                }
                $zone2 = '';
                //途经景点
                if ($this_line['sight_cache'] !== '') {
                        $this_line['sight_cache'] = str_replace('，', ',', $this_line['sight_cache']);
                        $this_line['sight_cache'] = str_replace(' ', ',', $this_line['sight_cache']);
                        $this_line['sight_cache'] = str_replace('、', ',', $this_line['sight_cache']);
                        $this_line['sight_t'] = explode(',', $this_line['sight_cache']);
                } else {
                        $this_line['sight_t'] = '';
                }
                //热门景点


                $zone = $zone2 ? $zone2 : $zone1;
                $this->assign('line', $this_line);
                //相关线路
                $list = $Tours->order("id desc")->where(array('cid' => array('like', "%," . $zone['id'] . ",%"), 'id' => array('neq', $this_line['id']), 'ischecked' => 1))->limit(5)->cache()->select();
                $this->assign('lines_list', $list);

                //在线咨询
                /* $counsel_list = D("ToursCounsel")->where(array('tours_id' => $this_line['id'], 'reply' => array('neq', '')))->order('create_time desc')->limit(6)->select();
                  $this->assign('counsel_list', $counsel_list);
                 * */


                //用户点评
                $count = M('Comment')->where(array('tours_id' => $this_line['id'], 'status' => '1'))->cache()->count();
                $url = 'tours/xianlu/' . $_REQUEST['id'] . '/';
                $page = new \org\Page($count, 5, '', $url, '', '#g');
                $counsel_list = M("Comment")->where(array('tours_id' => $this_line['id'], 'status' => '1'))->order('update_time desc')->limit($page->firstRow, $page->listRows)->cache()->select();
                if ($counsel_list !== false) {
                        $this->assign('page', $page->show());
                        $this->assign('comment', $counsel_list);
                }

                //SEO优化，生成TITLE,K,D
                $from = array('，', '{linename}', '{lineto}', '{linesub}');
                $to = array(',', $this_line['title'], $zone['name'], $this_line['subtitle']);
                $seo_title = $this_line['seo_title'] ? $this_line['seo_title'] : str_replace($from, $to, C('site.line_seotitle'));
                $seo_keywords = $this_line['seo_keywords'] ? $this_line['seo_keywords'] : str_replace($from, $to, C('site.line_seokeywords'));
                $seo_description = $this_line['seo_description'] ? $this_line['seo_description'] : str_replace($from, $to, C('site.line_seodescription'));
                $this->assign('seo_title', $seo_title);
                $this->assign('seo_keywords', $seo_keywords);
                $this->assign('seo_description', $seo_description);
                return $this->fetch();
        }

        public function print_trip() {
                if ($_REQUEST['id']) {
                        $this_line = D("Tours")->relation(true)->field(true)->find($_REQUEST['id']);
                        $this->assign('line', $this_line);
                        return $this->fetch("print");
                }
        }

        /**
         * 添加线路咨询
         */
        public function counsel_add() {

                $this->checkFatherUrl();
                $uid = session('uid');
                /*
                 * if (empty($uid))
                  return $this->error("uidnull", U('/tours/user/login', '', '', false, true));
                 * 
                 */
                $verify = new \org\Verify();
                if (IS_AJAX) {
                        if (!$verify->check(I('post.verify'), "tours"))
                                return $this->error("验证码错误");
                        $data = array();
                        if (!empty($uid)) {
                                $data['uid'] = session("uid");
                        } else {
                                $data['uid'] = 0;
                        }
                        $data['content'] = I('post.content');
                        $data['phone'] = I('post.phone');
                        $data['tours_id'] = I('post.line_id');
                        $data['create_time'] = time();
                        $ret = D("ToursCounsel")->add($data);
                        if ($ret !== false) {
                                return $this->success("potsucc");
                        } else {
                                return $this->error("potnull");
                        }
                } else {
                        return $this->_empty();
                }
        }

        public function add_recent() {
                $id = I('get.id');
                //点击数
                D("Tours")->where(array('id' => $id))->setInc('hits');
        }

        /**
         * 加入收藏
         */
        public function collect() {
                $this->checkFatherUrl();
                $uid = session("uid");
                $model = M("UserLine");
                if (empty($uid)) {
                        return $this->error("未登录", U('/tours/user/login', '', '', false, true));
                }
                if (IS_AJAX) {
                        $tours_id = I("id");
                        $userLine = $model->where(array('uid' => $uid, 'tours_id' => $tours_id))->find();
                        if (!empty($userLine))
                                return $this->error("您已收藏过了！");
                        $data['tours_id'] = $tours_id;
                        $data['uid'] = $uid;
                        $data['create_time'] = time();
                        $ret = $model->add($data);
                        if ($ret) {
                                return $this->success("已收藏，请到会员中心查看！");
                        } else {
                                return $this->error("收藏失败，请联系管理员！");
                        }
                } else {
                        $this->_empty();
                }
        }

        /**
         * 在线预订
         */
        public function book() {
                $step = I('get.step');
                switch ($step) {
                        case 1:
                                $verify = new \org\Verify();
                                if (IS_POST) {
                                        if (!$verify->check(I('post.verify'), "tours"))
                                                return $this->error("验证码错误");
                                        /* $uid = session('uid');
                                          if (empty($uid)) {
                                          $this->error("请先登录");
                                          }
                                          //添加订单
                                          $order = D("ToursOrder");
                                          $order_id = get_order_id();
                                          $o_data = array();
                                          $o_data['uid'] = $uid;
                                          $o_data['order_id'] = $order_id;
                                          $o_data['supplier_id'] = I("post.supplier_id");
                                          $o_data['tours_id'] = I("post.tours_id");
                                          $o_data['go_date'] = I("post.go_date");
                                          $o_data['insure_id'] = I("post.insure_id");
                                          $o_data['insure_num'] = I("post.insure_num");
                                          $o_data['insure_price'] = I("post.insure_price");
                                          $o_data['adult'] = I("post.adult");
                                          $o_data['adult_price'] = I("post.adult_price");
                                          $o_data['child'] = I("post.child");
                                          $o_data['child_price'] = I("post.child_price");
                                          $o_data['pregnantwoman'] = I("post.pregnantwoman") ? I("post.pregnantwoman") : "N";
                                          $o_data['olderman'] = I("post.olderman") ? I("post.olderman") : "N";
                                          $o_data['foreigners'] = I("post.foreigners") ? I("post.foreigners") : "N";
                                          $o_data['minors'] = I("post.minors") ? I("post.minors") : "N";
                                          $o_data['demand'] = I("post.demand");
                                          $o_data['create_time'] = time();
                                          $o_data['status'] = 0;
                                          $o_data['is_del'] = 0;
                                          $order->add($o_data);

                                          //添加会员
                                          $userInfo = D("UserInfo");
                                          $userName = $userInfo->where(array('user_id' => $uid))->find();
                                          if (empty($userName)) {
                                          $u_data = array();
                                          $u_data['user_id'] = $uid;
                                          $u_data['realname'] = I("post.linkname");
                                          $userInfo->add($u_data);
                                          }
                                          $this->redirect("/book/proc_success/" . $order_id);
                                          exit; */
                                        //添加会员
                                        $userInfo = D("User");
                                        $userName = $userInfo->where(array('mobile' => I('post.mobile')))->find();
                                        if (empty($userName)) {
                                                $u_data = array();
                                                $u_data['mobile'] = I('post.mobile');
                                                $u_data['username'] = I("post.linkname");
                                                $uid = $userInfo->add($u_data);
                                        } else {
                                                $u_data = array();
                                                $u_data['mobile'] = I('post.mobile');
                                                $u_data['username'] = I("post.linkname");
                                                $uid = $userInfo->where(array('mobile' => I('post.mobile')))->save($u_data);
                                        }
                                        //添加订单
                                        $order = D("ToursOrder");
                                        $order_id = get_order_id();
                                        $o_data = array();
                                        $o_data['uid'] = $uid;
                                        $o_data['order_id'] = $order_id;
                                        $o_data['supplier_id'] = I("post.supplier_id");
                                        $o_data['tours_id'] = I("post.tours_id");
                                        $o_data['go_date'] = I("post.go_date");
                                        $o_data['insure_id'] = I("post.insure_id");
                                        $o_data['insure_num'] = I("post.insure_num");
                                        $o_data['insure_price'] = I("post.insure_price");
                                        $o_data['adult'] = I("post.adult");
                                        $o_data['adult_price'] = I("post.adult_price");
                                        $o_data['child'] = I("post.child");
                                        $o_data['child_price'] = I("post.child_price");
                                        $o_data['pregnantwoman'] = I("post.pregnantwoman") ? I("post.pregnantwoman") : "N";
                                        $o_data['olderman'] = I("post.olderman") ? I("post.olderman") : "N";
                                        $o_data['foreigners'] = I("post.foreigners") ? I("post.foreigners") : "N";
                                        $o_data['minors'] = I("post.minors") ? I("post.minors") : "N";
                                        $o_data['demand'] = I("post.demand");
                                        $o_data['create_time'] = time();
                                        $o_data['status'] = 0;
                                        $o_data['is_del'] = 0;
                                        $order->add($o_data);


                                        $this->redirect("/book/proc_success/" . $order_id);
                                        exit;
                                } else {
                                        $id = I('get.id');
                                        $ordertime = I('get.ordertime');
                                        $price_id = I('get.price_id');
                                        $adults = I('get.adults');
                                        $childs = I('get.childs');

                                        //线路读取
                                        $tours = D("Tours");
                                        $line = $tours->relation(true)->field(true)->find($id);
                                        $cids_array = array_filter(explode(",", $line['cid']));
                                        $where['type'] = 1;
                                        if (in_array(2, $cids_array)) {
                                                $where['type'] = 2;
                                        } elseif (in_array(1, $cids_array)) {
                                                $where['type'] = 1;
                                        }
                                        $travelcontract = M("TravelContract")->where($where)->getField("content");
                                        $insure = M("ToursInsure")->field(true)->where(array('id' => $line['insure_id']))->find();
                                        $line['insure_name'] = $insure['name'];
                                        $line['insure_price'] = $insure['price'];
                                        $line['insure_deadline'] = $insure['deadline'];
                                        $line['insure_desc'] = $insure['desc'];
                                        $line['travelcontract'] = $travelcontract;
                                        $this->assign('line', $line);
                                        $this_price = $tours->getPriceByDay($ordertime, $price_id, "", true);
                                        $this->assign('price', $this_price);
                                        $this->assign('adults', $adults);
                                        $this->assign('childs', $childs);
                                        $this->assign('ordertime', $ordertime);
                                }
                                break;
                        case 2:
                                break;
                }

                return $this->fetch();
        }

        /**
         * 在线支付
         */
        public function onlinepay() {
                $this->checkUser();
                if (IS_POST) {
                        $order_id = I('post.order_id');
                        $pay_money = I('post.pay_money');
                        $pay_bank = I('post.pay_bank');
                        $line = D("ToursOrder")->relation(true)->where(array('order_id' => $order_id))->find();
                        $num = get_time_number();
                        //生成收款信息
                        $check = M("ToursPayment")->where(array('order_id' => $order_id))->setField('num', $num);
                        if ($check !== false) {
                                $alipay = new \org\Alipay();
                                $param = array(
                                    'order_id' => $num,
                                    'subject' => $line['title'],
                                    'prepay_ment' => $pay_money,
                                    'body' => $line['title'],
                                    'show_url' => $line['tours_url']
                                );
                                if ($pay_bank != "alipay") {
                                        $param["paymethod"] = "bankPay";
                                        $param["defaultbank"] = $pay_bank;
                                }
                                header("Content-type: text/html; charset=utf-8");
                                echo $alipay->buildRequestForm($param, "get");
                        }
                        exit;
                } else {
                        $uid = session('uid');
                        $orderid = I("get.orderid");
                        //订单判断
                        $order = D("ToursOrder")->relation(true)->where(array('order_id' => $orderid))->find();
                        if ($order['uid'] != $uid || $order['status'] != 2) {
                                $this->redirect("/");
                        }
                        $this->assign('order', $order);
                }

                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * 判断实际是否支付成功
         */
        public function GetPayStatus() {
                $order_id = I('get.orderid');
                $payment = M("ToursPayment")->where(array('order_id' => $order_id))->find();
                if ($payment['payment'] - $payment['paymoney'] <= 0) {
                        echo "1";
                } else {
                        echo "0";
                }
        }

        public function AlipayNotify() {
                $alipay = new \org\Alipay();
                $verify_result = $alipay->verifyNotify();
                if ($verify_result) {//验证成功
                        //支付宝交易号
                        $trade_no = $_POST['trade_no'];
                        //支付宝商户订单号
                        $out_trade_no = $_POST['out_trade_no'];
                        //买家支付宝用户号
                        $buyer_id = $_POST['buyer_id'];
                        //交易金额
                        $total_fee = $_POST['total_fee'];
                        if ($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {
                                $payment = M("ToursPayment")->where(array('num' => $out_trade_no))->find();
                                $yue = $payment['payment'] - $payment['paymoney'] - $total_fee;
                                if ($payment) {
                                        if ($payment['pay_status'] != 2) {
                                                $pay_data = array();
                                                $pay_data['pay_num'] = $trade_no;
                                                $pay_data['paymoney'] = $total_fee + $payment['paymoney'];
                                                $pay_data['payment_time'] = time();
                                                $pay_data['buyer_id'] = $buyer_id;
                                                if ($yue > 0) {
                                                        $pay_data['pay_status'] = 1;
                                                        $status = 3;
                                                }
                                                if ($yue <= 0) {
                                                        $pay_data['pay_status'] = 2;
                                                        $status = 4;
                                                }
                                                M("ToursPayment")->where(array('num' => $out_trade_no))->save($pay_data);
                                                M("ToursOrder")->where(array('order_id' => $payment['order_id']))->setField('status', $status);
                                        }
                                }
                        }
                        echo "success";
                } else {
                        //验证失败
                        echo "fail";
                }
        }

        /*
         * 切换价格
         */

        protected $show_week_ch = array('日', '一', '二', '三', '四', '五', '六');

        public function PriceCheck() {
                if (IS_AJAX) {
                        $price_id = I('post.price_id');
                        $tours_id = I('post.tours_id');
                        $result['tours_price'] = M('ToursPrice')->where(array('tours_id' => $tours_id))->cache()->select();
                        $leixin = M('ToursPrice')->where(array('id' => $price_id))->cache()->find();
                        $result['delay_time'] = array();

                        $this_year = date("Y");
                        $this_month = date("m");
                        $this_day = date("d");
                        $tn = 1;
                        for ($i = 1; $i <= 160; $i++) {
                                if ($tn > 30)
                                        break;
                                $show_day = date("Y-m-d", mktime($i * 24, 0, 0, $this_month, $this_day, $this_year));
                                $show_week = date("w", mktime($i * 24, 0, 0, $this_month, $this_day, $this_year));
                                $show_tian = date("d", mktime($i * 24, 0, 0, $this_month, $this_day, $this_year));
                                $show_week_ch = $this->show_week_ch[$show_week];
                                $show_day_time = strtotime($show_day);
                                if (!empty($result['tours_price'])) {
                                        $result['delay_time']['sprice'] = $leixin['sprice'];
                                        foreach ($result['tours_price'] as $key => $value) {
                                                //显示标签相同的第一个标签下的价格汇总
                                                if ($value['leixin'] == $leixin['leixin'] && $value['case_id'] == $leixin['case_id']) {
                                                        $value['price_value'] = unserialize($value['price_value']);
                                                        switch ($value['price_type']) {
                                                                case 1:
                                                                        if ($show_day_time >= strtotime($value['start_time']) && ($show_day_time <= strtotime($value['end_time']) || empty($value['start_time']))) {
                                                                                if ($value['price_value']['adult'] > 0) {
                                                                                        $result['delay_time'][$show_day] = $show_day . " （周" . $show_week_ch . "） " . $value['price_value']['adult'] . "元/人";

                                                                                        if ($value['price_value']['child'] > 0) {
                                                                                                $result['delay_time'][$show_day] .= " " . $value['price_value']['child'] . "元/儿童";
                                                                                        }

                                                                                        $tn++;
                                                                                        break 2;
                                                                                }
                                                                        }
                                                                        break;
                                                                case 2:
                                                                        if ($show_day_time >= strtotime($value['start_time']) && ($show_day_time <= strtotime($value['end_time']) || empty($value['start_time']))) {
                                                                                $value['price_value'] = array_values($value['price_value']);
                                                                                $adult_index = ($show_week - 1) < 0 ? 6 : ($show_week - 1);
                                                                                $child_index = ($show_week + 13 ) < 14 ? 20 : ($show_week + 13);
                                                                                if ($value['price_value'][$adult_index] > 0) {
                                                                                        $result['delay_time'][$show_day] = $show_day . " （周" . $show_week_ch . "） " . $value['price_value'][$adult_index] . "元/人";
                                                                                        if ($value['price_value'][$child_index] > 0) {
                                                                                                $result['delay_time'][$show_day] .= " " . $value['price_value'][$child_index] . "元/儿童";
                                                                                        }
                                                                                        $tn++;
                                                                                        break 2;
                                                                                }
                                                                        }
                                                                        break;
                                                                case 3:
                                                                        if ($show_day_time >= strtotime($value['start_time']) && ($show_day_time <= strtotime($value['end_time']) || empty($value['start_time']))) {
                                                                                foreach ($value['price_value']['day'] as $k => $val) {
                                                                                        if ($val == $show_tian && $value['price_value']['adult'][$k] > 0) {
                                                                                                $result['delay_time'][$show_day] = $show_day . " （周" . $show_week_ch . "） " . $value['price_value']['adult'][$k] . "元/人";
                                                                                                if ($value['price_value']['child'][$k] > 0) {
                                                                                                        $result['delay_time'][$show_day] .= " " . $value['price_value']['child'][$k] . "元/儿童";
                                                                                                }
                                                                                                $tn++;
                                                                                                break 3;
                                                                                        }
                                                                                }
                                                                        }
                                                                        break;
                                                                case 4:
                                                                        if ($show_day_time == strtotime($value['start_time'])) {
                                                                                if ($value['price_value']['adult'] > 0) {
                                                                                        $result['delay_time'][$show_day] = $show_day . " （周" . $show_week_ch . "） " . $value['price_value']['adult'] . "元/人";
                                                                                        if ($value['price_value']['child'] > 0) {
                                                                                                $result['delay_time'][$show_day] .= " " . $value['price_value']['child'] . "元/儿童";
                                                                                        }
                                                                                        $tn++;
                                                                                        break 2;
                                                                                }
                                                                        }
                                                                        break;
                                                        }
                                                }
                                        }
                                }
                        }
                        if (empty($result['delay_time']) || count($result['delay_time']) == 1) {
                                $result['delay_time'][0] = '固定日期发团';
                                $this->ajaxReturn($result['delay_time'], 'JSON');
                        } else {
                                $this->ajaxReturn($result['delay_time'], 'JSON');
                                exit();
                        }
                }
        }

        public function AlipayReturn() {
                $alipay = new \org\Alipay();
                $verify_result = $alipay->verifyReturn();
                if ($verify_result) {
                        //支付宝交易号
                        $trade_no = $_GET['trade_no'];
                        //支付宝商户订单号
                        $out_trade_no = $_GET['out_trade_no'];
                        //买家支付宝用户号
                        $buyer_id = $_GET['buyer_id'];
                        //交易金额
                        $total_fee = $_GET['total_fee'];

                        if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                                $payment = M("ToursPayment")->where(array('num' => $out_trade_no))->find();
                                $yue = $payment['payment'] - $payment['paymoney'] - $total_fee;
                                if ($payment) {
                                        if ($payment['pay_status'] != 2) {
                                                $pay_data = array();
                                                $pay_data['pay_num'] = $trade_no;
                                                $pay_data['paymoney'] = $total_fee + $payment['paymoney'];
                                                $pay_data['payment_time'] = time();
                                                $pay_data['buyer_id'] = $buyer_id;
                                                if ($yue > 0) {
                                                        $pay_data['pay_status'] = 1;
                                                        $status = 3;
                                                }
                                                if ($yue <= 0) {
                                                        $pay_data['pay_status'] = 2;
                                                        $status = 4;
                                                }
                                                M("ToursPayment")->where(array('num' => $out_trade_no))->save($pay_data);
                                                M("ToursOrder")->where(array('order_id' => $payment['order_id']))->setField('status', $status);
                                        }
                                }
                        }
                        return $this->redirect("user/lineorder");
                }
                return $this->redirect("/");
        }

}
